package com.nfc.demo;

import java.util.ArrayList;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import android.preference.PreferenceManager;
import android.widget.*;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.UiSettings;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class NFCTouristActivity extends Activity
{
	private Double mLatitude = null;
	private Double mLongitude = null;
	private String mTitle = "";
	private String mSnippet = "";
	private String mDescription = "";
	private ArrayList<String> mNames = new ArrayList<String>();
	private ArrayList<String> mVicinities = new ArrayList<String>();

	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		int selectedNavigationIndex = (savedInstanceState != null ? savedInstanceState.getInt("selectedNavigationIndex") : 0);
		Settings.mRadius = (savedInstanceState != null ? savedInstanceState.getInt("mRadius") : 5000);
		Settings.mTypes = (savedInstanceState != null ? savedInstanceState.getString("mTypes") : "");
		mNames = (savedInstanceState != null ? savedInstanceState.getStringArrayList("mNames") : new ArrayList<String>());
		mVicinities = (savedInstanceState != null ? savedInstanceState.getStringArrayList("mVicinities") : new ArrayList<String>());

		MyMapFragment mMapFragment = new MyMapFragment();
		mMapFragment.setInstance(MapFragment.newInstance());
		Fragment mInfoFragment = new InfoFragment();
		Fragment mSettingsFragment = new SettingsFragment();

		ActionBar bar = getActionBar();
		bar.setDisplayShowHomeEnabled(false);
		bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		bar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);

		ActionBar.Tab mapTab = bar.newTab().setText(R.string.TabMap);
		ActionBar.Tab infoTab = bar.newTab().setText(R.string.TabInfo);
		ActionBar.Tab settingsTab = bar.newTab().setText(R.string.TabSettings);

		mapTab.setTabListener(new TabListener(mMapFragment));
		infoTab.setTabListener(new TabListener(mInfoFragment));
		settingsTab.setTabListener(new TabListener(mSettingsFragment));

		setContentView(R.layout.main);

		bar.addTab(mapTab, 0, false);
		bar.addTab(infoTab, 1, false);
		bar.addTab(settingsTab, 2, false);

		bar.setSelectedNavigationItem(selectedNavigationIndex);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState)
	{
		super.onRestoreInstanceState(savedInstanceState);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState)
	{
		super.onSaveInstanceState(outState);

		outState.putInt("selectedNavigationIndex", getActionBar().getSelectedNavigationIndex());
		outState.putString("mTypes", Settings.mTypes);
		outState.putInt("mRadius", Settings.mRadius);
		outState.putStringArrayList("mNames", mNames);
		outState.putStringArrayList("mVicinities", mVicinities);
	}

	@Override
	protected void onResume()
	{
		super.onResume();
	}

	public void setContents()
	{
		readPreferences();
		
		if (getActionBar().getSelectedNavigationIndex() == 0)
		{
			readNdefContents();

			GoogleMap mMap;
			mMap = ((MyMapFragment) getFragmentManager().findFragmentById(R.id.fragmentContainer)).getMap();

			UiSettings uiSettings = mMap.getUiSettings();
			uiSettings.setCompassEnabled(true);
			mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

			if (mLatitude != null && mLongitude != null)
			{
				mMap.addMarker(new MarkerOptions().position(new LatLng(mLatitude, mLongitude))
						.title(mTitle)
						.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))
						.snippet(mSnippet));

				if (!Settings.mTypes.isEmpty())
				{
					new GetPlaces(NFCTouristActivity.this, Settings.mTypes, Settings.mRadius, mMap).execute();
				}

				CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(mLatitude, mLongitude))
						// Sets the center of the map
						.zoom(15.0f)
						// Sets the zoom
						// .tilt(30) // Sets the tilt of the camera to 30
						// degrees
						.build(); // Creates a CameraPosition from the builder
				mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

			}

		}
		else if (getActionBar().getSelectedNavigationIndex() == 1)
		{
			readNdefContents();

			TextView description = (TextView) findViewById(R.id.description);
			description.setText(mDescription);

			ListView listview = (ListView) findViewById(R.id.listview);
			MyArrayAdapter adapter = new MyArrayAdapter(this, mNames.toArray(new String[mNames.size()]), mVicinities.toArray(new String[mVicinities.size()]));
			listview.setAdapter(adapter);
		}
		else if (getActionBar().getSelectedNavigationIndex() == 2)
		{
		}

	}

	public void readNdefContents()
	{
		if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction()))
		{
			Parcelable[] rawMsgs = getIntent().getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
			if (rawMsgs != null)
			{
				NdefMessage[] msgs = new NdefMessage[rawMsgs.length];
				for (int i = 0; i < rawMsgs.length; i++)
				{
					msgs[i] = (NdefMessage) rawMsgs[i];
				}
				NdefRecord[] records = msgs[0].getRecords();
				for (int i = 0; i < records.length; i++)
				{
					NdefRecord record = records[i];
					String content = new String(record.getPayload());
					if (content != null)
					{
						String[] parts = content.split("&");
						if (parts.length >= 5)
						{
							mLatitude = Double.parseDouble(parts[0]);
							mLongitude = Double.parseDouble(parts[1]);
							mTitle = parts[2];
							mSnippet = parts[3];
							mDescription = parts[4];
						}
					}
				}
			}
		}
	}

	public class GetPlaces extends AsyncTask<Void, Void, ArrayList<Place>>
	{
		private GoogleMap mMap;
		private ProgressDialog dialog;
		private Context context;
		private String types;
		private int radius;

		public GetPlaces(Context context, String places, int radius, GoogleMap mMap)
		{
			this.context = context;
			this.types = places;
			this.radius = radius;
			this.mMap = mMap;
		}

		@Override
		protected void onPreExecute()
		{
			super.onPreExecute();
			dialog = new ProgressDialog(context);
			dialog.setCancelable(false);
			dialog.setMessage("Loading ..");
			dialog.isIndeterminate();
			dialog.show();
		}

		@Override
		protected ArrayList<Place> doInBackground(Void... arg0)
		{
			PlacesService service = new PlacesService("AIzaSyBcHSNekG_d0undTzJL0eVNVQNZpGOyqhs");
			ArrayList<Place> places = service.getPlaces(mLatitude, mLongitude, types, radius);
			mNames.clear();
			mVicinities.clear();
			for (int i = 0; i < places.size(); i++)
			{
				mNames.add(places.get(i).getName());
				mVicinities.add(places.get(i).getVicinity());
			}
			return places;
		}

		@Override
		protected void onPostExecute(ArrayList<Place> places)
		{
			super.onPostExecute(places);

			if (dialog.isShowing())
			{
				dialog.dismiss();
			}
			if (mMap != null)
			{
				for (int i = 0; i < places.size(); i++)
				{
					mMap.addMarker(new MarkerOptions().title(places.get(i)
							.getName())
							.position(new LatLng(places.get(i).getLatitude(), places.get(i).getLongitude()))
							.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin))
							.snippet(places.get(i).getVicinity()));
				}
			}
		}
	}

	protected class TabListener implements ActionBar.TabListener
	{
		private Fragment fragment;

		public TabListener(Fragment fragment)
		{
			this.fragment = fragment;
		}

		public void onTabSelected(Tab tab, FragmentTransaction fragmentTransaction)
		{
			fragmentTransaction.replace(R.id.fragmentContainer, this.fragment);
		}

		public void onTabUnselected(Tab tab, FragmentTransaction fragmentTransaction)
		{
			fragmentTransaction.remove(this.fragment);
		}

		public void onTabReselected(Tab tab, FragmentTransaction fragmentTransaction)
		{
		}
	}

	public void readPreferences()
	{

		SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);

		int radius = sharedPref.getInt(Settings.KEY_RADIUS, Settings.mRadius / 1000) * 1000;
		Settings.mRadius = radius;

		Settings.mTypes = "";

		boolean servicesAccommodation = sharedPref.getBoolean(Settings.KEY_SERVICES_ACCOMODATION, false);
		boolean servicesATMBank = sharedPref.getBoolean(Settings.KEY_SERVICES_ATMBANK, false);
		boolean servicesEmbassy = sharedPref.getBoolean(Settings.KEY_SERVICES_EMBASSY, false);
		boolean servicesHospital = sharedPref.getBoolean(Settings.KEY_SERVICES_HOSPITAL, false);
		boolean servicesPolice = sharedPref.getBoolean(Settings.KEY_SERVICES_POLICE, false);
		
		boolean attractionBarCafe = sharedPref.getBoolean(Settings.KEY_ATTRACTIONS_BARCAFE, false);
		boolean attractionCasino = sharedPref.getBoolean(Settings.KEY_ATTRACTIONS_CASINO, false);
		boolean attractionLibrary = sharedPref.getBoolean(Settings.KEY_ATTRACTIONS_LIBRARY, false);
		boolean attractionMuseum = sharedPref.getBoolean(Settings.KEY_ATTRACTIONS_MUSEUM, false);
		boolean attractionPark = sharedPref.getBoolean(Settings.KEY_ATTRACTIONS_PARK, false);
		boolean attractionRestaurant = sharedPref.getBoolean(Settings.KEY_ATTRACTIONS_RESTAURANT, false);
		boolean attractionStadium = sharedPref.getBoolean(Settings.KEY_ATTRACTIONS_STADIUM, false);
		
		boolean travelAirport = sharedPref.getBoolean(Settings.KEY_TRAVEL_TRAINSTATION, false);
		boolean travelBusStation = sharedPref.getBoolean(Settings.KEY_TRAVEL_BUSSTATION, false);
		boolean travelSubwayStation = sharedPref.getBoolean(Settings.KEY_TRAVEL_SUBWAYSTATION, false);
		boolean travelTaxiStand = sharedPref.getBoolean(Settings.KEY_TRAVEL_TAXISTAND, false);
		boolean travelTrainStation = sharedPref.getBoolean(Settings.KEY_TRAVEL_TRAINSTATION, false);

		if (servicesAccommodation) Settings.mTypes += "lodging|";
    	if (servicesATMBank) Settings.mTypes += "bank|atm|";
    	if (servicesEmbassy) Settings.mTypes += "embassy|";
    	if (servicesHospital) Settings.mTypes += "hospital|";
    	if (servicesPolice) Settings.mTypes += "police|";

    	if (attractionBarCafe) Settings.mTypes += "bar|cafe|";
    	if (attractionCasino) Settings.mTypes += "casino|";
    	if (attractionLibrary) Settings.mTypes += "library|";
    	if (attractionMuseum) Settings.mTypes += "museum|";
    	if (attractionPark) Settings.mTypes += "park|";
    	if (attractionRestaurant) Settings.mTypes += "restaurant|";
    	if (attractionStadium) Settings.mTypes += "stadium|";
    	
    	if (travelAirport) Settings.mTypes += "airport|";
    	if (travelBusStation) Settings.mTypes += "bus_station|";
    	if (travelSubwayStation) Settings.mTypes += "subway_station|";
    	if (travelTaxiStand) Settings.mTypes += "taxi_stand|";
    	if (travelTrainStation) Settings.mTypes += "train_station|";
	}
}